package timing.ukulele.third.controller.weixin;

import cn.hutool.core.text.StrPool;
import com.alibaba.fastjson2.JSON;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import org.springframework.web.bind.annotation.*;
import timing.ukulele.common.data.ResponseData;
import timing.ukulele.data.third.view.weixin.WxMessageTemplateParamVO;
import timing.ukulele.data.third.view.weixin.WxMessageTemplateVO;
import timing.ukulele.third.msgChannel.utils.AccountUtils;
import timing.ukulele.third.persistent.msg.MessageTemplate;
import timing.ukulele.third.service.msg.ChannelAccountService;
import timing.ukulele.third.service.msg.MessageTemplateService;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 微信模板消息管理
 * @author
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/weixin/wxMessageTemplate")
public class WxMessageTemplateController {

    private final AccountUtils accountUtils;

    private final ChannelAccountService channelAccountService;

    private final MessageTemplateService messageTemplateService;

    /**
     * /weixin/wxMessageTemplate/getWxMsgTemplateListByAccountId
     * @param accountId
     * @return
     */
	@Operation(summary = "根据账号Id获取微信消息模板列表")
    @PostMapping("/getWxMsgTemplateListByAccountId")
    public ResponseData<List<WxMessageTemplateVO>> getWxMsgTemplateListByAccountId(@RequestParam("accountId") Long accountId) {
        try {
            return ResponseData.success(getWxMessageTemplateList(accountId));
        }catch (Exception e) {
            return ResponseData.error("获取微信模板失败："+e.getMessage());
        }
    }

    private List<WxMessageTemplateVO> getWxMessageTemplateList(Long accountId) throws Exception {
        List<WxMessageTemplateVO> result = new ArrayList<>();
        // 查询账号信息
        WxMpService wxMpService = accountUtils.getAccountById(accountId, WxMpService.class);
        // 查询微信模板
        List<WxMpTemplate> allPrivateTemplateList = wxMpService.getTemplateMsgService().getAllPrivateTemplate();
        // 转化成系统需要数据格式
        for (WxMpTemplate wxMpTemplate : allPrivateTemplateList) {
            if(!wxMpTemplate.getTitle().equals("订阅模板消息")) {
                WxMessageTemplateVO wxMessageTemplateVO = handleWxMpTemplateParam(wxMpTemplate);
                result.add(wxMessageTemplateVO);
            }
        }
        return result;
    }

    /**
     * 将微信得到的模板参数转为系统需要的参数结构
     * @param wxMpTemplate
     * @return
     */
    private WxMessageTemplateVO handleWxMpTemplateParam(WxMpTemplate wxMpTemplate) {
        WxMessageTemplateVO wxMessageTemplateVO = new WxMessageTemplateVO();
        wxMessageTemplateVO.setId(wxMpTemplate.getTemplateId());
        wxMessageTemplateVO.setName(wxMpTemplate.getTitle());
        String[] data = wxMpTemplate.getContent().split(StrPool.LF);
        List<WxMessageTemplateParamVO> paramList = new ArrayList<>();
        for (String datum : data) {
            WxMessageTemplateParamVO param = new WxMessageTemplateParamVO();
            String label = null;
            if (datum.contains("first")) {
               label = "名字";
            } else if (datum.contains("remark")) {
               label = "备注";
            } else {
               label = datum.split(":")[0];
            }
            param.setLabel(label);
            String key = datum.substring(datum.indexOf("{{") + 2, datum.indexOf("."));
            param.setKey(key);
            paramList.add(param);
        }
        wxMessageTemplateVO.setParamList(paramList);
        return wxMessageTemplateVO;
    }

    public ResponseData<List<WxMessageTemplateVO>> getWxToSysMsgTemplateList( Long accountId,Long sysTemplateId) {
        try {
            List<WxMessageTemplateVO> wxMessageTemplateList = getWxMessageTemplateList(accountId);
            if(sysTemplateId != null) {
                // 查询系统模板
                MessageTemplate sysMessageTemplate = messageTemplateService.getById(sysTemplateId);
                WxMessageTemplateVO wxMessageTemplate = JSON.parseObject(sysMessageTemplate.getMsgContent(), WxMessageTemplateVO.class);
                wxMessageTemplateList.stream()
                        .map(item -> {
                            if (item.getId().equals(wxMessageTemplate.getTemplateId())) {
                                item.setTemplateId(wxMessageTemplate.getTemplateId());
                                item.setUrlType(wxMessageTemplate.getUrlType());
                                item.setUrl(wxMessageTemplate.getUrl());
                                item.setParamList(wxMessageTemplate.getParamList());
                            }
                            return item;
                        })
                        .collect(Collectors.toList());
                return ResponseData.success(wxMessageTemplateList);
            }else{
                return ResponseData.success(wxMessageTemplateList);
            }
        }catch (Exception e) {
            return ResponseData.error("获取微信模板失败："+e.getMessage());
        }
    }

}
